class Compiler {
    constructor(vm) {
        this.el = vm.$el
        this.$methods = vm.$methods
        this.vm = vm
        this.compile(this.el)
    }
    // 编译模板， 处理文本节点和元素节点
    compile(el) {
        let childNodes = el.childNodes
        Array.from(childNodes).forEach(node => {
            if(this.isTextNode(node)) {
                // 处理文本节点
                this.compileText(node)
            } else if(this.isElementNode(node)) {
                // 处理元素节点 
                this.compileElement(node)
            }
            // 判断node节点是否存在子节点，如果存在递归调用
            if(node.childNodes && node.childNodes.length) {
                this.compile(node)
            }
        })
    }

    // 编译元素节点，处理指令
    compileElement(node) {
        Array.from(node.attributes).forEach(attr => {
            let attrName = attr.name
            let eventName = ''
            if(this.isDirective(attrName)) {
                attrName = attrName.substr(2)
                if(attrName.indexOf(':')!==-1) {
                    attrName = attrName.substr(0,2)
                    eventName = attr.name.substr(5)
                }
                let key = attr.value 
                this.update(node, key, attrName, eventName)
            }
        })
    }

    update(node, key, attrName, eventName) {
        let updateFn = this[attrName + 'Updater']
        updateFn && updateFn.call(this, node, this.vm[key], key, eventName)
    }

    // v-text
    textUpdater(node, value, key) {
        node.textContent = value
        new Watcher(this.vm, key, (newVal)=>{
            node.textContent = newVal
        })
    }
    // v-html
    htmlUpdater(node, value, key) {
        node.innerHTML = value
        new Watcher(this.vm, key, (newVal)=>{
            node.innerHTML = newVal
        }) 
    }
    // v-model
    modelUpdater(node, value, key) {
        node.value = value
        new Watcher(this.vm, key, (newVal)=>{
            node.value = newVal
        })
        // 双向绑定
        node.addEventListener('input', ()=> {
            this.vm[key] = node.value
        })
    }
    // v-on
    onUpdater(node, value, key, eventName) {
        node.addEventListener(eventName, this.$methods[key])
    }

    // 编译文本节点，处理插值表达式
    compileText(node) {
        let reg = /\{\{(.+?)\}\}/
        let value = node.textContent
        if(reg.test(value)) {
            let key = RegExp.$1.trim()
            node.textContent = value.replace(reg, this.vm[key])

            // 创建watcher对象，当数据改变时更新视图
            new Watcher(this.vm, key, (newVal) => {
                node.textContent = newVal 
            })
        }
    }

    // 判断元素属性是否是指令
    isDirective(attrName) {
        return attrName.startsWith('v-')
    }
    // 判断节点是否是文本节点
    isTextNode(node) {
        return node.nodeType === 3
    }
    // 判断节点是否是元素节点
    isElementNode(node) {
        return node.nodeType === 1
    }
}